﻿using Microsoft.Extensions.Options;
using System.Linq;
using System.Threading.Tasks;
using Volo.Abp.Application.Dtos;
using Xms.Abp.Application.Dtos;
using Xms.Abp.Application.Services;
using Xms.Abp.Authorization;
using Xms.Abp.Settings;

namespace SettingsManagement;

[PermissionsUse(typeof(SettingsPermissions))]
public class SettingsManagementAppService : XmsApplicationService, ISettingsManagementAppService
{
    internal protected virtual SettingsOptions Options => LazyInject<IOptions<SettingsOptions>>().Value;
    internal protected virtual ISettingsManager SettingsManager => LazyInject<ISettingsManager>();

    public virtual async Task<SettingsInfoResult> GetAsync(string providerName, string providerKey, string typeName)
    {
        var settingsInfo = await SettingsManager.GetSettingsInfoAsync(typeName, providerName, providerKey);
        return ObjectMapper.MapTo<SettingsInfoResult>(settingsInfo);
    }

    public virtual async Task<PagedResultDto<SettingsInfoListResult>> GetListAsync(string providerName, PagedSortedAndFilterParameter parameter)
    {
        var all = SettingsManager.GetEditableSettingsTypes(providerName);
        var count = all.Count;
        var list = all.Skip(parameter.SkipCount).Take(parameter.SkipCount).ToList();
        var items = ObjectMapper.MapTo<SettingsInfoListResult>(list);
        var page = new PagedResultDto<SettingsInfoListResult>(count, items);
        return await Task.FromResult(page);
    }

    public virtual async Task ResetAsync(string providerName, SettingsResetParameter parameter)
    {
        await SettingsManager.ResetAsync(parameter.TypeName, providerName, parameter.ProviderKey);
    }

    public virtual async Task SetAsync(string providerName, SettingsUpdateParameter parameter)
    {
        var values = new SettingsValues
        {
            Values = parameter.Values.Select(r => new SettingValue(r.Name, r.Value)).ToList(),
            Dictionaries = parameter.Dictionaries.ToDictionary(r => r.Key, r => r.Value.Select(s => new SettingValue(s.Name, s.Value)).ToList())
        };
        await SettingsManager.SetAsync(parameter.TypeName, values, providerName, parameter.ProviderKey);
    }
}
